<?php

namespace App\Services\SysManage;


use App\Models\ChatKeyRoom;

use App\Models\SysParams;

use App\Models\WebsocketServer;
use App\Services\BaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class SysService
{

    //获取系统参数
    public function getSysParam($param){
        $param_data_array = [];
        $param_array = explode(',', $param);

        foreach ($param_array as $value){
            $key = BaseService::REDIS_KEY_PREFIX_SYS_PARAM . $value;
            $param_data = Redis::get($value);
            if ($param_data == null || $param_data == "null"){
                //查无当前系统字，需要重新添加到redis中
                $sysparam_str = SysParams::where('name', $value)->first();

                Redis::set($key, json_encode($sysparam_str, true));
                Redis::expire($key, 24 * 3600);
                $sysparam_array = json_decode($sysparam_str, true);
            }else {
                $sysparam_array = json_decode($param_data, true);//第二个参数true表示转换成数组
            }
            array_push($param_data_array, $sysparam_array);
        }
        return $param_data_array;
    }

    /*
     * 检查服务器各个聊天连接数
     * */
    function checkServerLink($room_max){
        $websocket = WebsocketServer::where(['type'=> 1, 'status'=>1])->get();

        $flag= false;
        foreach ($websocket as $value) {
            $sum_num = $room_max + $value->room_sum_num;
            if($sum_num < $value->server_max_num) {
                $websocket_url = $value->url;
                $websocket_id = $value->id;
                $flag = true;
                WebsocketServer::where('id', $value->id)->update(['room_sum_num' => $sum_num]);
                break;
            }
        }
        if($flag) {
            $result = [];
            $result['ws_server_url'] = $websocket_url;
            $result['ws_server_id'] = $websocket_id;
            return $result;
        }else {
            return null;
        }
        //之后要进行添加

    }

    /*
     * 关闭房间后还原连接数
     * */
    function reduceServerLink($ws_server_id,$room_id){
        $chatRoom = ChatKeyRoom::find($room_id);
        $wsServer = WebsocketServer::find($ws_server_id);
        if($chatRoom->enable == ChatRoom::ENABLE_OFF){
            $wsServer->room_sum_num = $wsServer->room_sum_num - $chatRoom->room_max_num;
            $wsServer->save();
            return true;
        }else{
            return false;
        }

    }

}